import React, { useEffect, useRef } from 'react';
import { Switch, InputNumber } from 'antd';
import http from '@/services/request';
import * as echarts from 'echarts';

let option = {
  title: {
    text: '实时温湿度检测',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      animation: false
    }
  },
  legend: {
    data: ['Temperature', 'Humidity'],
    left: 10
  },
  toolbox: {
    feature: {
      dataZoom: {
        yAxisIndex: 'none'
      },
      restore: {},
      saveAsImage: {}
    }
  },
  axisPointer: {
    link: [
      {
        xAxisIndex: 'all'
      }
    ]
  },
  dataZoom: [
    {
      show: true,
      realtime: true,
      xAxisIndex: [0, 1]
    },
    {
      type: 'inside',
      realtime: true,
      xAxisIndex: [0, 1]
    }
  ],
  grid: [
    {
      left: 60,
      right: 50,
      height: '35%'
    },
    {
      left: 60,
      right: 50,
      top: '55%',
      height: '35%'
    }
  ],
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      axisLine: { onZero: true },
      data: []
    },
    {
      gridIndex: 1,
      type: 'category',
      boundaryGap: false,
      axisLine: { onZero: true },
      data: [],
      position: 'top'
    }
  ],
  yAxis: [
    {
      name: 'Temperature(°C)',
      type: 'value',
      max: 50
    },
    {
      gridIndex: 1,
      name: 'Humidity(RH)',
      type: 'value',
      inverse: true
    }
  ],
  series: [
    {
      name: 'Temperature',
      type: 'line',
      symbolSize: 8,
      // prettier-ignore
      data: [],
      markArea: {
        itemStyle: {
          color: 'rgba(255, 173, 177, 0.4)'
        },
        data: []
      }
    },
    {
      name: 'Humidity',
      type: 'line',
      xAxisIndex: 1,
      yAxisIndex: 1,
      symbolSize: 8,
      // prettier-ignore
      data: [],
      markArea: {
        itemStyle: {
          color: 'rgba(255, 173, 177, 0.4)'
        },
        data: []
      }
    }
  ]
};

export default function InfraredTemperatureAndHealthHumidityMonitorEarlyWarning() {
  const RefTemperature = useRef<HTMLDivElement | HTMLElement | object | any>(
    null
  );
  const RefHumidity = useRef<HTMLDivElement | HTMLElement | object | any>(null);
  const DayTemperature = useRef<HTMLDivElement | HTMLElement | object | any>(
    null
  );
  const temperatureRef = useRef<HTMLDivElement | HTMLElement | object | any>(
    null
  );
  const temperatureLessRef = useRef<
    HTMLDivElement | HTMLElement | object | any
  >(null);
  const humidityRef = useRef<HTMLDivElement | HTMLElement | object | any>(null);
  const humidityLessRef = useRef<HTMLDivElement | HTMLElement | object | any>(null);
  let myChartD;
  let chartDom;
  let switchValue = true;
  const renderPie = async () => {
    const seriesTemperatureData: number[] = [];
    const seriesHumidityData: number[] = [];
    const dateArr: string[] = [];
    await http
      .get('/hardware/temperatureAndHumidity/temperatureAndHumidityAvgQuery')
      .then((res) => {
        const { data } = res;
        data.forEach((item) => {
          seriesTemperatureData.push(item['avg-temperature']);
          seriesHumidityData.push(item['avg-humidity']);
          dateArr.push(item['date']);
        });
      });
    setTimeout(async () => {
      echarts.init(RefTemperature.current);
      type EChartsOption = echarts.EChartsOption;
      var chartDomT = document.getElementById('pieT')!;
      var myChartT = echarts.init(chartDomT);
      var optionT: EChartsOption;

      optionT = {
        title: {
          text: '各鸡舍当前的温度情况：'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {},
        toolbox: {
          show: true,
          feature: {
            dataView: {
              readOnly: false,
              title: '查看数据',
              lang: ['数据视图', '关闭', '刷新']
            },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dateArr
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} °C'
          }
        },
        series: [
          {
            name: '当前鸡舍的温度情况如下：',
            type: 'line',
            data: seriesTemperatureData,
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            }
          }
        ]
      };

      optionT && myChartT.setOption(optionT);
    }, 0);
    // 湿度
    setTimeout(() => {
      echarts.init(RefHumidity.current);
      type EChartsOption = echarts.EChartsOption;
      var chartDomH = document.getElementById('pieH')!;
      var myChartH = echarts.init(chartDomH);
      var optionH: EChartsOption;
      optionH = {
        title: {
          text: '各鸡舍当前的湿度情况：'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {},
        toolbox: {
          show: true,
          feature: {
            dataView: {
              readOnly: false,
              title: '查看数据',
              lang: ['数据视图', '关闭', '刷新']
            },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dateArr
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} RH'
          }
        },
        series: [
          {
            name: '当前鸡舍的湿度情况如下：',
            type: 'line',
            data: seriesHumidityData,
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            }
          }
        ]
      };

      optionH && myChartH.setOption(optionH);
    }, 0);
  };

  const reSizeChart = (option) => {
    if (!myChartD) {
      chartDom = document.getElementById('pieD')!;
      myChartD = echarts.init(chartDom as HTMLElement);
      myChartD = echarts.getInstanceByDom(chartDom);
    }
    myChartD.setOption(option);
  };

  const fetchTodayData = async () => {
    if (!switchValue) {
      return;
    }
    await http.get('/hardware/temperatureAndHumidity/today').then((res) => {
      const { data } = res;
      const timeData: any[] = [];
      const tempValue: any[] = [];
      const humidityValue: any[] = [];
      const tempWaring: any[] = [];
      let tempwarnArr: any[] = [];
      let tempwarnLessArr: any[] = [];
      let isTempContinueOver = false;
      let isTempContinueLess = false;
      const humiditywarnArr: any[] = [];
      let humidityMoreArr: any[] = [];
      let humidityLessArr: any[] = [];
      let ishumidityOver = false;
      let ishumidityLess = false;
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        timeData.push(item['save-datetime']);
        tempValue.push(Number(item.temperature));
        humidityValue.push(Number(item.humidity));
        if (Number(item.temperature) < temperatureLessRef.current.value) {
          if (!isTempContinueLess) {
            tempwarnLessArr.push({
              name: '温度过低',
              xAxis: item['save-datetime']
            });
            isTempContinueLess = true;
          }
        } else {
          if (isTempContinueLess) {
            tempwarnLessArr.push({
              xAxis: item['save-datetime']
            });
            isTempContinueLess = false;
            tempWaring.push(tempwarnLessArr);
            tempwarnLessArr = [];
          }
        }
        if (Number(item.temperature) > temperatureRef.current.value) {
          if (!isTempContinueOver) {
            tempwarnArr.push({
              name: '温度过高',
              xAxis: item['save-datetime']
            });
            isTempContinueOver = true;
          }
        } else {
          if (isTempContinueOver) {
            tempwarnArr.push({
              xAxis: item['save-datetime']
            });
            isTempContinueOver = false;
            tempWaring.push(tempwarnArr);
            tempwarnArr = [];
          }
        }
        if (Number(item.humidity) < humidityLessRef.current.value) {
          if (!ishumidityLess) {
            humidityLessArr.push({
              name: '湿度过低',
              xAxis: item['save-datetime']
            });
            ishumidityLess = true;
          }
        } else {
          if (ishumidityLess) {
            humidityLessArr.push({
              xAxis: item['save-datetime']
            });
            ishumidityLess = false;
            humiditywarnArr.push(humidityLessArr);
            humidityLessArr = [];
          }
        }
        if (Number(item.humidity) > humidityRef.current.value) {
          if (!ishumidityOver) {
            humidityMoreArr.push({
              name: '湿度过高',
              xAxis: item['save-datetime']
            });
            ishumidityOver = true;
          }
        } else {
          if (ishumidityOver) {
            humidityMoreArr.push({
              xAxis: item['save-datetime']
            });
            ishumidityOver = false;
            humiditywarnArr.push(humidityMoreArr);
            humidityMoreArr = [];
          }
        }
      }
      if (tempwarnArr.length !== 0) {
        tempwarnArr.push({
          xAxis: data[data.length - 1 || 0]['save-datetime']
        });
        isTempContinueOver = false;
        tempWaring.push(tempwarnArr);
        tempwarnArr = [];
      }

      if (tempwarnLessArr.length !== 0) {
        tempwarnLessArr.push({
          xAxis: data[data.length - 1 || 0]['save-datetime']
        });
        isTempContinueLess = false;
        tempWaring.push(tempwarnLessArr);
        tempwarnLessArr = [];
      }

      if (humidityMoreArr.length !== 0) {
        humidityMoreArr.push({
          xAxis: data[data.length - 1 || 0]['save-datetime']
        });
        ishumidityOver = false;
        humiditywarnArr.push(humidityMoreArr);
        humidityMoreArr = [];
      }

      if (humidityLessArr.length !== 0) {
        humidityLessArr.push({
          xAxis: data[data.length - 1 || 0]['save-datetime']
        });
        ishumidityLess = false;
        humiditywarnArr.push(humidityLessArr);
        humidityLessArr = [];
      }
      setTimeout(async () => {
        (option.xAxis[0].data as any[]) = timeData;
        (option.xAxis[1].data as any[]) = timeData;
        (option.series[0].data as any[]) = tempValue;
        (option.series[1].data as any[]) = humidityValue;
        if (option.series[0].markArea) {
          if (tempWaring.length > 0) {
            (option.series[0].markArea.data as any[]) = tempWaring;
          } else {
            (option.series[0].markArea.data as any[]) = [];
          }
        }
        if (option.series[1].markArea) {
          if (humiditywarnArr.length > 0) {
            (option.series[1].markArea.data as any[]) = humiditywarnArr;
          } else {
            (option.series[1].markArea.data as any[]) = [];
          }
        }
        reSizeChart(option);
      }, 0);
    });
  };

  const onChange = (e) => {
    switchValue = e;
  };

  useEffect(() => {
    renderPie();
    fetchTodayData();
    let timer = setInterval(() => {
      fetchTodayData();
    }, 2000);
    return () => {
      clearInterval(timer);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div>
      <h3>实时温湿度监测：(温度单位:°C,湿度单位:%rh)</h3>
      实时开关：
      <Switch defaultChecked onChange={onChange} />
      <span style={{ margin: '0 20px' }}>
        温度过高预警值：
        <InputNumber ref={temperatureRef} addonAfter="°C" defaultValue={30} />
      </span>
      <span style={{ margin: '0 20px' }}>
        温度过低预警值：
        <InputNumber
          ref={temperatureLessRef}
          addonAfter="°C"
          defaultValue={15}
        />
      </span>
      <span style={{ margin: '0 20px' }}>
        湿度过高预警值：
        <InputNumber ref={humidityRef} addonAfter="%RH" defaultValue={80} />
      </span>
      <span style={{ margin: '0 20px' }}>
        湿度过低预警值：
        <InputNumber ref={humidityLessRef} addonAfter="%RH" defaultValue={60} />
      </span>
      <div
        ref={DayTemperature}
        id="pieD"
        style={{
          height: '800px',
          marginTop: '50px',
          width: '100%'
        }}
      />
      <h3>7天平均温湿度监测：(温度单位:°C,湿度单位:%rh)</h3>
      <div
        ref={RefTemperature}
        id="pieT"
        style={{
          height: '400px',
          marginTop: '50px',
          width: '100%'
        }}
      />
      <div
        ref={RefHumidity}
        id="pieH"
        style={{
          height: '400px',
          marginTop: '30px',
          width: '100%'
        }}
      />
    </div>
  );
}
